package de.preamp.clients.java.lib;

import java.io.IOException;
import java.util.SortedSet;
import java.util.TreeSet;

import javax.annotation.PostConstruct;
import javax.swing.event.ChangeEvent;

import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import de.preamp.clients.java.data.Artist;
import de.preamp.clients.java.net.ServerConnection;

/**
 * A class managing the media-library using the preamp server and local cache.
 * It is the top level container keeping all library elements in a tree
 * structure beginning with artists and followed by albums and tracks. It can be
 * used as a kind of proxy object to the database.
 * 
 * @author André Stannek
 * @version 2011-06-11
 */
@Component("rootLibrary")
public class RootLibrary extends AbstractLibrary
{
    /**
     * Generated UID.
     */
    private static final long serialVersionUID = -2305669336723124086L;

    /**
     * the artists available in this library from the id3 TPE1 fields.
     */
    private transient SortedSet<Artist> artists;

    /**
     * 
     */
    @Autowired(required = true)
    private transient ServerConnection serverConnection;

    @Override
    @PostConstruct
    public final void update() throws JSONException, IOException
    {
	try
	{
	    artists = new TreeSet<Artist>(serverConnection.getAllArtists());
	    for (final Artist artist : artists)
	    {
		artist.addChangeListener(this);
		this.add(getSize(), artist);
	    }
	}
	catch (final Exception e)
	{
	}
    }

    @Override
    public final void stateChanged(final ChangeEvent event)
    {
	final int index = this.indexOf(event.getSource());
	fireContentsChanged(this, index, index + 1);
    }
}
